package com.pfc.wifiscan;


import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.Toast;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;

import com.pfc.others.FileManagement;
import com.pfc.others.GPSManagement;
import com.pfc.others.SQLiteManagement;
import com.pfc.wifiscan.R;

public class ChangeLocationActivity extends Activity {
	
	public String locationName;
	public boolean selected; 			// solo para pruebas, para poder probar la aplicacion en un lugar unicamente
	public CheckBox checkBoxClicked;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_changelocation);
		this.locationName = getIntent().getStringExtra("location");
		System.out.println("location en change activity: "+this.locationName);
		listLocations();
		this.selected=false;
	}
	
	public void listLocations(){
		SQLiteManagement sql = new SQLiteManagement(getApplicationContext());
		double[] coordNow = new GPSManagement().getCoordinates(this.getApplicationContext());
		sql.open();
		ArrayList<String> list= sql.getLocationsName();
		sql.close();
		TableLayout tableL = (TableLayout)findViewById(R.id.listTableLoc);
		
		OnClickListener listener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                   CheckBox cb = (CheckBox) v;
                   if(cb.isChecked()){
                	   locationName = cb.getText().toString();
                	   checkBoxClicked.setChecked(false);
                	   checkBoxClicked = cb;
                	   System.out.println("cambio de location: "+locationName);
                   } 
            }
      };
		if (list.isEmpty()){
			final String message = "no hay localizaciones guardadas";
			TextView text =(TextView)findViewById(R.id.textLocation);
			text.setText(message);
			text.setTextSize(15);
			text.setFocusable(true);
			text.setVisibility(View.VISIBLE);
		}
		else{
			for (int i=0 ; i<list.size(); i++){
				String loc = list.get(i);
				TableRow tableR = new TableRow(getApplicationContext());
				CheckBox checkB = new CheckBox(getApplicationContext());
				checkB.setOnClickListener(listener);
				checkB.setText(loc);
				checkB.setChecked(false);
				
				// comprobamos que la localizacion actual coincida con alguna localizacion guardada (GPS)
				sql.open();
				double[] coordFromLocation = sql.getCoordinatesFromLocation(loc);
				sql.close();
				if (new GPSManagement().areIqualCoordinates(coordFromLocation, coordNow) && locationName==null && !selected){
					checkB.setChecked(true);
					checkBoxClicked = checkB;
					selected = true;
					this.locationName = loc;
				}
				else if (locationName.equals(loc)){
					checkB.setChecked(true);
					checkBoxClicked = checkB;
					selected = true;
					this.locationName = loc;
				}

				ImageButton buttonDelete = new ImageButton(getApplicationContext());
				buttonDelete.setImageResource(android.R.drawable.ic_delete);
				buttonDelete.setVisibility(View.VISIBLE);
				buttonDelete.setFocusable(true);
				buttonDelete.setOnClickListener(new OnClickListener() {
				    public void onClick(View v){
				    	// borramos la localizacion en la BD y los ficheros asociados a dicha localizacion
				        double resultDelete = 0;
				        SQLiteManagement sql = new SQLiteManagement(getApplicationContext());
				        sql.open();
				        resultDelete = sql.deleteLocation(locationName);
				        sql.close();
				        if (resultDelete==-1){
				        	//error al borrar los datos de un lugar
				        	Toast.makeText(getApplicationContext(),"Error al borrar la zona.",Toast.LENGTH_LONG).show();
				        }
				        FileManagement fm = new FileManagement(getApplicationContext());
				        fm.deleteAllFilesFromLocation(locationName);
				        Intent i = new Intent(v.getContext(), ChangeLocationActivity.class);
				        i.putExtra("location", locationName);
						startActivity(i);
				    } 
				});
				;
				tableR.addView(checkB, (new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)));
				tableR.addView(buttonDelete, (new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)));
				tableL.addView(tableR, (new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)));
			}
		}
	}
	
	
	public void addLocation(View view){
		TextView textNoLocations = (TextView)findViewById(R.id.textLocation);
		textNoLocations.setVisibility(View.INVISIBLE);
		EditText text = (EditText)findViewById(R.id.edit_location);
		Button buttonAccept = (Button)findViewById(R.id.button_addLocation);
		text.setVisibility(view.VISIBLE);
		buttonAccept.setVisibility(view.VISIBLE);
	}
	
	
	public void saveLocation(View view){
		double valido = 0;
		EditText text = (EditText)findViewById(R.id.edit_location);
		String nameLoc = text.getEditableText().toString();
		if (nameLoc.equals("")){
			Toast.makeText(this,"Error. La localizacion no puede estar vacia.",Toast.LENGTH_LONG).show();
		}
		else{ // guardamos la localizacion y sus coordenadas GPS
			double[] coordinates = new GPSManagement().getCoordinates(this.getApplicationContext());
			SQLiteManagement sql = new SQLiteManagement(getApplicationContext());
			sql.open();
			valido = sql.insertNewLocation(nameLoc, coordinates[0], coordinates[1]);
			sql.close();
			if (valido==-1){
				Toast.makeText(this,"Error. La localizacion no es valida.",Toast.LENGTH_LONG).show();
			}
			else{ 
				this.locationName = nameLoc;
			}
			Intent i = new Intent(this, ChangeLocationActivity.class);
			i.putExtra("location", this.locationName);
			startActivity(i);
		}
	}
	
	@Override
	public void onBackPressed() {
		Intent i = new Intent(this, ConfigActivity.class);
		i.putExtra("location", this.locationName);
		startActivity(i);
	}	
	
	/*
	public double[] getCoordinates(){
	     // Get the location manager
	     double[] coordinates = new double[2];
		 LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
		 Criteria criteria = new Criteria();
		 String bestProvider = locationManager.getBestProvider(criteria, false);
		 Location location = locationManager.getLastKnownLocation(bestProvider);
		 if (location!=null) {
	       coordinates[0] = location.getLongitude();	//-3
	       coordinates[1] = location.getLatitude();		//40
	     }
	     else{
	    	coordinates[0] = 0.0;
		    coordinates[1] = 0.0;	
	     	Toast.makeText(this,"GSP no disponible",Toast.LENGTH_LONG).show();
	     }
	     return coordinates;
    }*/
	
	
	
	
}
